package ywu.tools.timesync.ntp;

import java.nio.ByteBuffer;
import java.util.Date;

import ywu.tools.timesync.TimeSync;
import android.util.Log;

public class NtpResponse extends NtpDatagram
{
    /**
     * 客户端接收到应答报文的时间。
     */
    private long clientReceiveTimestamp = System.currentTimeMillis();

    public void fromByteBuffer(final ByteBuffer buf)
    {
        buf.flip();

        byte cur = buf.get();
        leapIndicator = (byte) (cur >>> 6);
        version = (byte) ((cur >>> 3) & 7); // 7 is 0111
        mode = (byte) (cur & 7); // 7 is 0111

        rootDelay = buf.getInt(4);
        referenceClock = fromNtpTimestamp(buf.getLong(16));
        receiveTimestamp = fromNtpTimestamp(buf.getLong(32));
        transmitTimestamp = fromNtpTimestamp(buf.getLong(40));
    }

    /**
     * 计算应该采用的新的系统时间.
     *
     * @param originateTs
     * @return
     */
    public long calcSystemTime(final long originateTs)
    {
        long rtt = clientReceiveTimestamp - originateTs; // Roundtrip Time of network transmition
        long ts = referenceClock + rtt / 2; // 以RTT的一半作为网络传输的单向时延(Server->Client)

        Log.d(TimeSync.TAG, "rtt(ms) = " + rtt + ", new SystemTime is " + DATE_FORMAT.format(new Date(ts)));
        return ts;
    }
}
